<?php
class Comment extends AppModel {

    public $validate = array(
    'created' => array('notEmpty'),
    'text' => array('notEmpty'),
    'article_id' => array('numeric'),
    'user_name' => array('notEmpty'),
    'title' => array('notEmpty'),
    'captcha' => array(
    'rule' => array('captcha','captcha'),
    'message' => 'Captcha answer is not correct'
    ),
    'badinput' => array(
    'rule' => array('blank'),
    'on' => 'create'
    ),
    'user_ip' => array(
    'rule' => array('blacklist','user_ip')
    )
    );

    public $belongsTo = array(
    'Article' =>
    array('className' => 'Article',
    'foreignKey' => 'article_id',
    'conditions' => '',
    'fields' => '',
    'order' => '',
    'counterCache' => ''
    ),

    'User' =>
    array('className' => 'User',
    'foreignKey' => 'user_id',
    'conditions' => '',
    'fields' => '',
    'order' => '',
    'counterCache' => ''
    ),

    );

    /**
     * validation method for captcha
     * @param $data - data to be valid
     * @param $fieldName - name of the field
     * @return <boolean>
     */
    public function captcha($data, $fieldName) {
        $valid = false;
        if(isset($fieldName)) {
            if (strtolower($data['captcha']) == Configure::read('Captcha.answer')) {
                $valid = true;
            }
        }
        return $valid;
    }

    /**
     * validation method for ip blacklist
     * @param $data - data to be valid
     * @param $fieldname - name of the field
     * @return <boolean>
     */
    public function blacklist($data, $fieldname) {
        App::Import('Model', 'Blacklist');
        $blacklist = new Blacklist();
        return !$blacklist->check($data['user_ip']);
    }

    public function find_all() {
        return $this->findAll(array('Comment.antispam is null or Comment.antispam=""'),null,array('Comment.created'=>'desc'));
    }

    public function last() {
        return $this->findAll(array('Comment.antispam is null or Comment.antispam=""'),array('Comment.user_name','Comment.id','Article.created','Article.seo_link','Article.title'),'Comment.created desc',Configure::read('Homepage.comments'));
    }
}
?>